#!/bin/bash

# 设置默认参数
NVME_DEVICE="/dev/nvme0n1"           # 默认的 NVMe 设备
PORT_ID="1"                           # 默认端口 ID
IP_ADDRESS="10.1.1.1"                 # 默认的 IP 地址
TRANSPORT_TYPE="rdma"                 # 默认的传输类型
TRANSPORT_SERVICE_ID="4420"           # 默认的服务端口
ADDRESS_FAMILY="ipv4"                 # 默认的地址族

# 显示帮助信息
function show_help {
    echo "Usage: \$0 [-d NVME_DEVICE] [-p PORT_ID] [-i IP_ADDRESS] [-t TRANSPORT_TYPE] [-s TRANSPORT_SERVICE_ID] [-v ADDRESS_FAMILY]"
    echo "  -d NVME_DEVICE            NVMe device (default: /dev/nvme0n1)"
    echo "  -p PORT_ID                Port ID (default: 1)"
    echo "  -i IP_ADDRESS             IP address (default: 10.1.1.1)"
    echo "  -t TRANSPORT_TYPE         Transport type (default: rdma)"
    echo "  -s TRANSPORT_SERVICE_ID   Transport service ID (default: 4420)"
    echo "  -v ADDRESS_FAMILY         Address family (default: ipv4)"
    echo "  -h                        Display this help message"
}

# 允许用户通过命令行参数修改默认值
while getopts "d:p:i:t:s:v:h" opt; do
  case $opt in
    d) NVME_DEVICE=$OPTARG ;;
    p) PORT_ID=$OPTARG ;;
    i) IP_ADDRESS=$OPTARG ;;
    t) TRANSPORT_TYPE=$OPTARG ;;
    s) TRANSPORT_SERVICE_ID=$OPTARG ;;
    v) ADDRESS_FAMILY=$OPTARG ;;
    h) show_help; exit 0 ;;
    *) show_help; exit 1 ;;
  esac
done

# 自动生成 SUBSYSTEM_NAME
SUBSYSTEM_NAME="${PORT_ID}-${NVME_DEVICE##*/}-${TRANSPORT_TYPE}"

# 加载必要的模块
modprobe nvme
modprobe nvmet
modprobe nvme-rdma
modprobe nvmet-rdma

# 创建并配置 Subsystem 和 Namespace
mkdir -p /sys/kernel/config/nvmet/subsystems/$SUBSYSTEM_NAME
echo 1 > /sys/kernel/config/nvmet/subsystems/$SUBSYSTEM_NAME/attr_allow_any_host
mkdir -p /sys/kernel/config/nvmet/subsystems/$SUBSYSTEM_NAME/namespaces/1
echo $NVME_DEVICE > /sys/kernel/config/nvmet/subsystems/$SUBSYSTEM_NAME/namespaces/1/device_path
echo 1 > /sys/kernel/config/nvmet/subsystems/$SUBSYSTEM_NAME/namespaces/1/enable

# 创建并配置端口
mkdir -p /sys/kernel/config/nvmet/ports/$PORT_ID
echo $IP_ADDRESS > /sys/kernel/config/nvmet/ports/$PORT_ID/addr_traddr
echo $TRANSPORT_TYPE > /sys/kernel/config/nvmet/ports/$PORT_ID/addr_trtype
echo $TRANSPORT_SERVICE_ID > /sys/kernel/config/nvmet/ports/$PORT_ID/addr_trsvcid
echo $ADDRESS_FAMILY > /sys/kernel/config/nvmet/ports/$PORT_ID/addr_adrfam

# 关联 Subsystem 和 Port
ln -s /sys/kernel/config/nvmet/subsystems/$SUBSYSTEM_NAME /sys/kernel/config/nvmet/ports/$PORT_ID/subsystems/$SUBSYSTEM_NAME

# 输出信息
# echo "NVMe over RoCE 配置完成："
dmesg -T | grep "enabling port"
